<template>
  <!-- eslint-disable vue/max-attributes-per-line -->
  <!-- eslint-disable vue/html-indent -->
  <!-- eslint-disable vue/html-self-closing -->
  <!-- eslint-disable vue/html-closing-bracket-newline -->
  <div>
    <el-form :model="spu" label-width="80px">
      <el-form-item label="SPU名称">
        <el-input v-model="spu.spuName" placeholder="SPU名称" />
      </el-form-item>
      <el-form-item label="品牌">
        <el-select v-model="spu.tmId" placeholder="请选择品牌" value="">
          <el-option
            v-for="tm in tradeMarkList"
            :key="tm.id"
            :label="tm.tmName"
            :value="tm.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input
          v-model="spu.description"
          placeholder="描述"
          rows="4"
          type="textarea"
        />
      </el-form-item>
      <el-form-item label="SPU图片">
        <el-upload
          :file-list="spuImageList"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
        >
          <i class="el-icon-plus" />
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img :src="dialogImageUrl" alt="" width="100%" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select
          v-model="attrIdAndAttrName"
          :placeholder="`还有${unSelectSaleAttr.length}未选择`"
        >
          <el-option
            v-for="unSelect in unSelectSaleAttr"
            :key="unSelect.id"
            :label="unSelect.name"
            :value="`${unSelect.id}:${unSelect.name}`"
          />
        </el-select>
        <el-button
          :disabled="!attrIdAndAttrName"
          icon="el-icon-plus"
          style="margin-left: 10px"
          type="primary"
          @click="addSaleAttr"
          >添加销售属性
        </el-button>
        <el-table
          :data="spu.spuSaleAttrList"
          border
          style="width: 100%; margin-top: 10px"
        >
          <el-table-column
            align="center"
            label="序号"
            type="index"
            width="80"
          />
          <el-table-column label="属性名" prop="saleAttrName" />
          <el-table-column label="属性值名称列表">
            <template slot-scope="{ row }">
              <el-tag
                v-for="(tag, index) in row.spuSaleAttrValueList"
                :key="tag.id"
                :disable-transitions="false"
                closable
                @close="row.spuSaleAttrValueList.splice(index, 1)"
              >
                {{ tag.saleAttrValueName }}
              </el-tag>
              <!--@close="handleClose(tag)"-->
              <el-input
                v-if="row.inputVisible"
                ref="saveTagInput"
                v-model="row.inputValue"
                class="input-new-tag"
                size="small"
                @blur="handleInputConfirm(row)"
              />
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="addSaleAttrValue(row)"
                >添加</el-button
              >
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="{ $index }">
              <el-button
                icon="el-icon-delete"
                size="mini"
                type="danger"
                @click="spu.spuSaleAttrList.splice($index, 1)"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addOrUpdateSpu">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
/* eslint-disable spaced-comment */
/* eslint-disable eqeqeq */
/* eslint-disable comma-dangle */
/* eslint-disable quotes */
/* eslint-disable semi */
export default {
  name: "SpuForm",
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      spu: {
        category3Id: 0,
        description: "",
        spuName: "",
        tmId: "",
        spuImageList: [],
        spuSaleAttrList: [
          {
            baseSaleAttrId: 0,
            id: 0,
            saleAttrName: "string",
            spuId: 0,
            spuSaleAttrValueList: [
              {
                baseSaleAttrId: 0,
                id: 0,
                isChecked: "string",
                saleAttrName: "string",
                saleAttrValueName: "string",
                spuId: 0,
              },
            ],
          },
        ],
      }, // 存储SPU信息属性
      tradeMarkList: [], // 品牌的信息
      spuImageList: [], // 存储SPU图片
      saleAttrList: [], // 销售属性
      attrIdAndAttrName: "", // 收集未选择的销售属性的id
    };
  },
  computed: {
    unSelectSaleAttr() {
      return this.saleAttrList.filter((item) => {
        return this.spu.spuSaleAttrList.every((item1) => {
          return item.name !== item1.saleAttrName;
        });
      });
    },
  },
  methods: {
    handleRemove(file, fileList) {
      this.spuImageList = fileList;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 初始化SpuForm数据
    async initSpuData(spu) {
      // 获取SPU信息
      await this.$API.spu.reqSpu(spu.id).then((result) => {
        if (result.code === 200) {
          this.spu = result.data;
        }
      });
      // 获取品牌信息
      await this.$API.spu.reqTradeMarkList().then((result) => {
        if (result.code === 200) {
          this.tradeMarkList = result.data;
        }
      });
      // 获取spu图片
      await this.$API.spu.reqSpuImageList(spu.id).then((result) => {
        if (result.code === 200) {
          result.data.forEach((item) => {
            item.name = item.imgName;
            item.url = item.imgUrl;
          });
          this.spuImageList = result.data;
        }
      });
      // 获取平台全部销售属性
      await this.$API.spu.reqBaseSaleAttrList().then((result) => {
        if (result.code === 200) {
          this.saleAttrList = result.data;
        }
      });
    },
    // 照片墙图片上传成功的回调
    handleSuccess(response, file, fileList) {
      this.spuImageList = fileList;
    },
    // 添加新的销售属性
    addSaleAttr() {
      const [baseSaleAttrId, saleAttrName] = this.attrIdAndAttrName.split(":");
      const newSaleAttr = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: [],
      };
      this.spu.spuSaleAttrList.push(newSaleAttr);
      this.attrIdAndAttrName = "";
    },
    // 添加按钮的回调
    addSaleAttrValue(row, index) {
      this.$set(row, "inputVisible", true);
      this.$set(row, "inputValue", "");
      this.$nextTick(() => {
        this.$refs.saveTagInput.focus();
      });
    },
    // el-put失去焦点事件
    handleInputConfirm(row) {
      const newSaleAttrValue = {
        baseSaleAttrId: row.baseSaleAttrId,
        saleAttrValueName: row.inputValue,
      };
      // 新增的销售属性值不能为空
      if (row.inputValue.trim() === "") {
        this.$message({
          type: "error",
          message: "属性值不能为空",
        });
        row.inputVisible = false;
        row.inputValue = "";
        return;
      }
      // 属性值不能重复
      const result = row.spuSaleAttrValueList.every((item) => {
        return item.saleAttrValueName !== row.inputValue;
      });
      if (!result) {
        this.$message({
          type: "error",
          message: "属性值不能重复",
        });
        row.inputVisible = false;
        row.inputValue = "";
        return;
      }
      row.spuSaleAttrValueList.push(newSaleAttrValue);
      row.inputVisible = false;
    },
    // 保存按钮的回调
    async addOrUpdateSpu() {
      this.spu.spuImageList = this.spuImageList.map((item) => {
        return {
          imageName: item.name,
          imageUrl: (item.response && item.response.data) || item.url,
        };
      });
      await this.$API.spu.reqAddOrUpdateSpu(this.spu).then((result) => {
        if (result.code == 200) {
          this.$message({
            type: "success",
            message: "保存成功",
          });
          this.$emit("changeScene", {
            scene: 0,
            flag: this.spu.id ? "修改" : "添加",
          });
        }
      });
      Object.assign(this._data, this.$options.data());
    },
    //点击添加SPU按钮的时候发请求
    async addSpuData(category3Id) {
      this.spu.category3Id = category3Id;
      // 获取品牌信息
      await this.$API.spu.reqTradeMarkList().then((result) => {
        if (result.code === 200) {
          this.tradeMarkList = result.data;
        }
      });
      // 获取平台全部销售属性
      await this.$API.spu.reqBaseSaleAttrList().then((result) => {
        if (result.code === 200) {
          this.saleAttrList = result.data;
        }
      });
    },
    //取消按钮
    cancel() {
      this.$emit("changeScene", { scene: 0, flag: "" });
      Object.assign(this._data, this.$options.data());
    },
  },
};
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
